from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

import time
import random
from datetime import datetime

import util.wugu as wugu
import util.mydecorator

import pandas as pd


driver = webdriver.Chrome()

driver.set_window_position(0, 0)
driver.maximize_window()   #最大化窗口

def get_data(stock):

    stock_name = stock['name']
    stock_code = stock['trade_code']

    url = "https://www.wogoo.com/hq/" + stock_code.replace('.XSHG','SH').replace('.XSHE','SZ')

    driver.get(url)

    wait = WebDriverWait(driver, 10)
    wait.until(EC.presence_of_element_located((By.CLASS_NAME, "score-num")))


    # 吾股
    #wugo = driver.find_element_by_class_name("score-num")
    wugo = driver.find_element(By.CLASS_NAME, "score-num")

    # 所属行业
    #industry = driver.find_element_by_xpath('//*[@id="NUXT_CONTAINER"]/div/main/div[2]/div/div[2]/div[2]/div[1]/div[2]/div[2]/span[2]')
    industry = driver.find_element(By.XPATH,'//*[@id="NUXT_CONTAINER"]/div/main/div[2]/div/div[2]/div[2]/div[1]/div[2]/div[2]/span[2]')

    # 行业排名
    #rank = driver.find_element_by_xpath('//*[@id="NUXT_CONTAINER"]/div/main/div[2]/div/div[2]/div[2]/div[1]/div[2]/div[1]/span[2]/span[1]')
    rank = driver.find_element(By.XPATH,'//*[@id="NUXT_CONTAINER"]/div/main/div[2]/div/div[2]/div[2]/div[1]/div[2]/div[1]/span[2]/span[1]')

    # 总市值
    #total = driver.find_element_by_xpath('//*[@id="NUXT_CONTAINER"]/div/main/div[1]/section[1]/div[3]/div[4]/div[3]/span')
    total = driver.find_element(By.XPATH, '//*[@id="NUXT_CONTAINER"]/div/main/div[1]/section[1]/div[3]/div[4]/div[3]/span')

    # 流通市值
    #noLimit = driver.find_element_by_xpath('//*[@id="NUXT_CONTAINER"]/div/main/div[1]/section[1]/div[3]/div[3]/div[3]/span')
    noLimit = driver.find_element(By.XPATH,'//*[@id="NUXT_CONTAINER"]/div/main/div[1]/section[1]/div[3]/div[3]/div[3]/span')

    print(stock_name,"吾股分数",wugo.text, "所属行业", industry.text, "行业排名", rank.text, "总市值",total.text, "流通市值", noLimit.text)

    time.sleep(random.randint(3,5))
    return {'stock':stock_name, 
            '吾股':int(wugo.text), 
            "industry": industry.text, 
            "行业排名": int(rank.text),
            "总市值": total.text, 
            "流通市值": noLimit.text
            }


@util.mydecorator.calTime
def job():

    date = datetime.now()

    n = 135
    df = wugu.get_data(n)

    ret = pd.DataFrame({},columns=['stock','吾股','industry','行业排名',"总市值","流通市值"])

    for index, row in df.iterrows():
        try:
            item = get_data(row)
            ret.loc[len(ret)] = item
        except Exception as e:
            print("exception", row, e)

    ret['datetime'] = date.strftime('%Y-%m-%d %H:%M:%S')
    ret.to_excel("data/wugo.xlsx")

    driver.close()   #关闭窗口


if __name__ == '__main__':
    job()


